package com.wzdigit.wms.raw.service.initialize.test;

import com.wzdigit.framework.Shift;


import com.wzdigit.wms.common.entity.StatusCode;
import com.wzdigit.wms.common.utils.HttpExcel;
import com.wzdigit.wms.raw.client.request.initialize.test.AsnImportInsertService;
import com.wzdigit.wms.raw.client.request.initialize.test.AsnInmportRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by zyf on 2021/8/30 20:18
 */
@Service
public class AsnImportTestService {
    @Autowired
    private AsnImportInsertService insertService;

    public List<String> imoprtAsnTest(MultipartFile file,
                                      HttpServletRequest servletRequest,
                                      HttpServletResponse servletResponse){
        String loginName="system";
        List<AsnInmportRequest> excel = null;
        try {
            InputStream inputStream = file.getInputStream();
            String[] properties = { "gdnNo", "vendorCode", "vendorName", "createUser",
                    "createTimeStr", "gdnLineNoStr", "factory", "erpCode", "skuCode", "skuDesc"
                    , "orderQtyStr", "rcvTimeStr"};
            excel = HttpExcel.importExcel(inputStream, AsnInmportRequest.class, properties);
        } catch (Exception e) {
            // 模板错误，请确认
            e.printStackTrace();
            Shift.fatal(StatusCode.IMPORT_DATA_ERROR);
        }
        if (excel == null || excel.size() == 0) {
            // 该模板数据为空
            Shift.fatal(StatusCode.IMPORT_DATA_NULL);
        }
        List<String> errors = new ArrayList<>();
        List<AsnInmportRequest> excelList;
        //根据asnNo分组
        Map<String, List<AsnInmportRequest>> headerMap = excel.stream().collect(Collectors.groupingBy(AsnInmportRequest::getGdnNo));
        for (Map.Entry<String, List<AsnInmportRequest>> entry : headerMap.entrySet()) {
            try {
                insertService.tryInsertGdn(entry.getValue());
            }catch (Exception e){
                errors.add(e.toString());
            }
        }
        return errors;
    }



}
